﻿using System;
using TechnicalIndicators.Points;
using Utils;

namespace TechnicalIndicators.DateBased
{
	public class Accumulator : GeneratorBase<DatedSeriePoint, DatedSeriePoint>
	{
		#region Attributes

		private TimeSpan _groupingRange;
		private DateTime? _currentTime;
		private decimal _currentValue;

		#endregion

		#region Public Methods

		public Accumulator(ObservableCollection2<DatedSeriePoint> destination) : base(destination)
		{
		}

		public void Configure(int period)
		{
			_groupingRange = TimeSpan.FromSeconds(period);
		}

		public override void Clear()
		{
			_currentTime = null;
			_currentValue = 0;

			base.Clear();
		}

		protected override DatedSeriePoint CreatePoint(DatedSeriePoint sourcePoint)
		{
			DatedSeriePoint result = null;

			if (_currentTime == null)
			{
				_currentTime = sourcePoint.X;
				_currentValue += sourcePoint.Y;
			}
			else if (sourcePoint.X - _currentTime.Value >= _groupingRange)
			{
				result = new DatedSeriePoint(_currentTime.Value, _currentValue);
				_currentTime = sourcePoint.X;
				_currentValue = 0;
			}
			else
			{
				_currentValue += sourcePoint.Y;
			}

			return result;
		}

		#endregion
	}
}
